package com.yumingjiang.weichatgtp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.yumingjiang.commontool.util.HttpClientResult;
import com.yumingjiang.commontool.util.StringUtil;
import com.yumingjiang.weichatgtp.common.exception.BizException;
import com.yumingjiang.weichatgtp.common.thread.AbstractRunnable;
import com.yumingjiang.weichatgtp.common.thread.TheadPoolExecutorUtil;
import com.yumingjiang.weichatgtp.service.FileService;
import org.springframework.stereotype.Service;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * [一句话描述该类的功能]
 *
 * @author : [Administrator]
 * @version : [v1.0]
 * @createTime : [2023/3/12 3:29]
 */
@Service
public class FileServiceImpl implements FileService {
    private final ThreadPoolExecutor EXECUTOR = TheadPoolExecutorUtil.getInstance().getThreadPoolExecutor();

    @Override
    public void writeToFile(String question, HttpClientResult httpClientResult, String fileName) {

        EXECUTOR.execute(new AbstractRunnable(fileName + " 写出") {
            @Override
            protected void runDo() {
                String result = "";
                if (httpClientResult.isSuccess()) {
                    if (StringUtil.isJSONString(httpClientResult.getContent())) {
                        result = JSONObject.parseObject(httpClientResult.getContent()).getString("result");
                    } else {
                        result = httpClientResult.getContent();
                    }
                } else {
                    result = question + " : " + httpClientResult.getMessage();
                }
                write(result, fileName);
            }
        });
    }


    private void write(String result, String fileName) {
        File file = new File(fileName);
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            FileWriter fileWriter = new FileWriter(file);
            BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
            bufferedWriter.write(result);
            bufferedWriter.flush();
            bufferedWriter.close();

        } catch (IOException e) {
            throw new BizException("### 文件写出失败", e);
        }
    }
}
